import { PlusOutlined } from "@ant-design/icons";
import { Input, InputRef, Tag } from "antd";
import { useEffect, useRef } from "react";
import { useSetState } from "react-use";

export const TagList: React.FC<{
  value?: string[];
  onChange?: (tags: string[]) => void;
}> = ({ value: tags = [], onChange }) => {
  const inputRef = useRef<InputRef>(null);
  const editInputRef = useRef<InputRef>(null);

  const [state, setState] = useSetState({
    inputVisible: false,
    editInputValue: "",
    editInputKey: -1,
  });

  useEffect(() => {
    if (state.inputVisible) {
      inputRef.current?.focus();
    }
  }, [state.inputVisible]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [state.editInputKey]);

  const inputStyle: React.CSSProperties = {
    width: 64,
    height: 24,
    marginInlineEnd: 8,
  };

  return (
    <div className="flex items-center flex-wrap">
      {tags.map((tag, k) =>
        state.editInputKey === k ? (
          <Input
            key={k}
            ref={editInputRef}
            type="text"
            size="large"
            style={inputStyle}
            value={state.editInputValue}
            onChange={(evt) => setState({ editInputValue: evt.target.value })}
            onBlur={() => {
              if (editInputRef.current?.input?.value) {
                const newTags = [...tags];
                newTags[state.editInputKey] =
                  editInputRef.current?.input?.value;
                onChange?.(newTags);
              }
              setState({ editInputKey: -1 });
            }}
          />
        ) : (
          <Tag
            key={k}
            closeIcon
            style={{ userSelect: "none" }}
            onClick={() => {
              setState({ editInputKey: k, editInputValue: tag });
            }}
            onClose={(evt) => {
              evt.preventDefault();
              onChange?.(tags.filter((t) => t !== tag));
            }}
          >
            {tag}
          </Tag>
        )
      )}
      {state.inputVisible ? (
        <Input
          ref={inputRef}
          type="text"
          style={inputStyle}
          onBlur={(e) => {
            const inputValue = e.target.value;
            if (inputValue && tags.indexOf(inputValue) === -1) {
              onChange?.([...tags, inputValue]);
            }
            setState({ inputVisible: false });
          }}
        />
      ) : (
        <Tag
          className="border-dashed cursor-pointer"
          onClick={() => {
            setState({ inputVisible: true });
          }}
        >
          添加
          <PlusOutlined />
        </Tag>
      )}
    </div>
  );
};
